'use client';

import { useState, useEffect } from 'react';
import { LeaderboardEntry } from '@/types';

interface Props {
  categoryId: string | null;
}

export default function Leaderboard({ categoryId }: Props) {
  const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchLeaderboard();
  }, [categoryId]);

  const fetchLeaderboard = async () => {
    try {
      setLoading(true);
      const url = categoryId
        ? `/api/leaderboard?categoryId=${categoryId}`
        : '/api/leaderboard';
      const res = await fetch(url);
      const data = await res.json();
      if (data.success) {
        setLeaderboard(data.leaderboard);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="card">
        <div>加载中...</div>
      </div>
    );
  }

  return (
    <div className="card">
      <h2 style={{ marginBottom: '20px' }}>排行榜</h2>
      {leaderboard.length === 0 ? (
        <p>暂无排行榜数据</p>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ backgroundColor: '#f5f5f5' }}>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>排名</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>用户名</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>总积分</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>最高分</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>最佳时间</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>挑战次数</th>
              </tr>
            </thead>
            <tbody>
              {leaderboard.map((entry, index) => (
                <tr key={entry.userId} style={{ borderBottom: '1px solid #eee' }}>
                  <td style={{ padding: '10px' }}>
                    {index === 0 && '🥇'}
                    {index === 1 && '🥈'}
                    {index === 2 && '🥉'}
                    {index >= 3 && index + 1}
                  </td>
                  <td style={{ padding: '10px' }}>{entry.username}</td>
                  <td style={{ padding: '10px' }}>{entry.points}</td>
                  <td style={{ padding: '10px' }}>{entry.bestScore}/10</td>
                  <td style={{ padding: '10px' }}>{entry.bestTime}秒</td>
                  <td style={{ padding: '10px' }}>{entry.totalChallenges}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

